import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'
import checkPermission from '@/utils/permission' // 权限判断函数
import { companySelfAssList, doCheck, downloadCompanySelfAss } from '@/api/company_self_ass'
import { getCompany } from '@/api/account'
import axios from 'axios'
import { getFileType, isImage, isMsOfficeFile, isPdf } from '@/utils/index'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

// 默认查询条件
const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: '-updated_time',
  company_name: undefined,
  check_status: undefined
}

export default {
  components: { Pagination, ElImageViewer },
  directives: { permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'primary',
        1: 'success',
        2: 'danger',
        3: 'warning'
      }
      return statusMap[status]
    },
    textFilter(status) {
      const statusMap = {
        0: '待检查',
        1: '通过',
        2: '需修改',
        3: '已修改'
      }
      return statusMap[status]
    },
    fileStatusFilter(fileList) {
      if (fileList && fileList.length > 0) {
        return 'primary'
      } else {
        return 'danger'
      }
    },
    fileTextFilter(fileList) {
      if (fileList && fileList.length > 0) {
        return '已上传'
      } else {
        return '未上传'
      }
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      // 查询条件
      listQuery: Object.assign({}, defaultListQuery),
      dialogVisible: false,
      checkForm: { check_status: undefined, check_opinion: undefined, is_check: true },
      rules: {
        check_opinion: [
          { required: true, message: '该项为必填项', trigger: 'blur' }
        ],
        check_status: [
          { required: true, message: '该项为必填项', trigger: 'change' }
        ]
      },
      companyList: [],
      previewImg: false,
      imgUrl: '',
      temp: {
        category_1_f: {
          'category_1_1': [],
          'category_1_2': [],
          'category_1_3': []
        },
        category_2_f: {
          'category_2_1': [],
          'category_2_2': [],
          'category_2_3': [],
          'category_2_4': [],
          'category_2_5': []
        },
        category_3_f: {
          'category_3_1': [],
          'category_3_2': [],
          'category_3_3': [],
          'category_3_4': []
        },
        category_4_f: {
          'category_4_1': [],
          'category_4_2': [],
          'category_4_3': [],
          'category_4_4': [],
          'category_4_5': [],
          'category_4_6': [],
          'category_4_7': []
        },
        category_5_f: {
          'category_5_1': [],
          'category_5_2': []
        },
        category_6_f: {
          'category_6_1': [],
          'category_6_2': []
        },
        category_7_f: {
          'category_7_1': [],
          'category_7_2': [],
          'category_7_3': []
        },
        category_8_f: {
          'category_8_1': []
        }
      },
      checkStatusList: [
        { name: '待检查', value: 0 },
        { name: '通过', value: 1 },
        { name: '需要修改', value: 2 },
        { name: '已修改', value: 3 }
      ],
      tableHeader: [
        { label: '1-1', key1: 'category_1', key2: 'category_1_1' },
        { label: '1-2', key1: 'category_1', key2: 'category_1_2' },
        { label: '1-3', key1: 'category_1', key2: 'category_1_3' },
        { label: '2-1', key1: 'category_2', key2: 'category_2_1' },
        { label: '2-2', key1: 'category_2', key2: 'category_2_2' },
        { label: '2-3', key1: 'category_2', key2: 'category_2_3' },
        { label: '2-4', key1: 'category_2', key2: 'category_2_4' },
        { label: '2-5', key1: 'category_2', key2: 'category_2_5' },
        { label: '3-1', key1: 'category_3', key2: 'category_3_1' },
        { label: '3-2', key1: 'category_3', key2: 'category_3_2' },
        { label: '3-3', key1: 'category_3', key2: 'category_3_3' },
        { label: '3-4', key1: 'category_3', key2: 'category_3_4' },
        { label: '4-1', key1: 'category_4', key2: 'category_4_1' },
        { label: '4-2', key1: 'category_4', key2: 'category_4_2' },
        { label: '4-3', key1: 'category_4', key2: 'category_4_3' },
        { label: '4-4', key1: 'category_4', key2: 'category_4_4' },
        { label: '4-5', key1: 'category_4', key2: 'category_4_5' },
        { label: '4-6', key1: 'category_4', key2: 'category_4_6' },
        { label: '4-7', key1: 'category_4', key2: 'category_4_7' },
        { label: '5-1', key1: 'category_5', key2: 'category_5_1' },
        { label: '5-2', key1: 'category_5', key2: 'category_5_2' },
        { label: '6-1', key1: 'category_6', key2: 'category_6_1' },
        { label: '6-2', key1: 'category_6', key2: 'category_6_2' },
        { label: '7-1', key1: 'category_7', key2: 'category_7_1' },
        { label: '7-2', key1: 'category_7', key2: 'category_7_2' },
        { label: '7-3', key1: 'category_7', key2: 'category_7_3' },
        { label: '8-1', key1: 'category_8', key2: 'category_8_1' }
      ]
    }
  },
  created() {
    this.getCompany()
    this.getList()
  },
  watch: {
  },
  methods: {
    checkPermission,

    gotoForm() {
      this.$router.push({
        name: 'CompanyForm'
      })
    },

    getCompany() {
      getCompany().then(res => {
        this.companyList = res
      })
    },

    viewDetail(row) {
      this.dialogVisible = true
      this.temp = Object.assign({}, row)
      this.checkForm = {
        check_status: row.check_status,
        check_opinion: row.check_opinion,
        id: row.id
      }
      if (row.check_status) this.checkForm.check_status = row.check_status
      this.$nextTick(function() {
        if (this.$refs['checkForm']) {
          this.$refs['checkForm'].clearValidate()
        }
      })
    },

    // 前往修改
    goChange(row) {
      this.$router.push({
        name: 'CompanyFormUpdate',
        query: { 'id': row.id }
      })
    },

    // 进行审核
    doCheck() {
      this.checkForm.is_check = true
      this.$refs['checkForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          doCheck(this.checkForm.id, this.checkForm).then(response => {
            loading.close()
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '检查成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        }
      })
    },

    // 下载文件
    downloadFile(file) {
      const url = file.url
      const filename = file.name
      const fileType = getFileType(url)
      if (isPdf(fileType)) {
        axios({
          url: url,
          method: 'get',
          responseType: 'blob'
        }).then(res => {
          console.log(res)
          // var filename = res.headers
          // filename = filename['content-disposition']
          // filename = filename.split(';')[1].split('filename=')[1]
          // filename = decodeURIComponent(filename) // 将utf-8解码

          const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }))

          const link = document.createElement('a')

          link.style.display = 'none'

          link.href = url

          link.setAttribute('download', filename)

          document.body.appendChild(link)

          link.click()

          document.body.removeChild(link)
        })
      } else {
        window.open(url)
      }
    },
    // 文件在线预览
    onlineRead(file) {
      const url = file.url
      const fileType = getFileType(url)
      if (isMsOfficeFile(fileType)) {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + url)
      } else if (isImage(fileType)) {
        this.imgUrl = url
        console.log(this.imgUrl)
        this.previewImg = true
      } else {
        window.open(url)
      }
    },
    // 关闭预览图片
    closePreviewImage() {
      this.previewImg = false
    },

    // 获取表格数据
    getList() {
      this.listLoading = true
      companySelfAssList(this.listQuery).then(res => {
        this.list = res.results
        this.total = res.count
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },

    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    formatData(data) {
      for (var key in data) {
        if (data[key] === '') {
          data[key] = undefined
        }
      }
    },

    // 下载查询结果Excel
    downloadExcel() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var listQuery = Object.assign({}, this.listQuery)
      listQuery.page = undefined
      listQuery.limit = undefined
      listQuery.download = true
      downloadCompanySelfAss(listQuery).then(res => {
        var filename = res.headers
        filename = filename['content-disposition']
        filename = filename.split(';')[1].split('filename=')[1]
        filename = decodeURIComponent(filename) // 将utf-8解码

        const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))

        const link = document.createElement('a')

        link.style.display = 'none'

        link.href = url

        link.setAttribute('download', filename)

        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)

        loading.close()
        this.downloadLoading = false
      }).catch(res => {
        loading.close()
      })
    },

    openDetail(data) {
      this.$alert(data, '检查意见', {
        showConfirmButton: false,
        closeOnClickModal: true,
        closeOnPressEscape: true
      })
    }

  }
}
